package com.sfang.common.util.validation;

import com.sfang.common.base.entity.RestInfo;
import com.sfang.common.util.http.RestfulUtil;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

public class ValidatorUtil {

    public static <T> RestInfo validateParams(T t, Class classType) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> violations = validator.validate(t, classType);

        if (violations != null && violations.size() > 0)
            return RestfulUtil.failRes(violations.stream().findAny().get().getMessage(),0,t);
        else
            return RestfulUtil.successRes();
    }
}
